<template>
    <!-- 全部客户 -->
    <div class="app-container" v-loading="loading">
        <!-- 搜索栏部分 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px "
            class="frominfo">
            <el-form-item label="微信名称" prop="wcUserName">
                <el-input v-model="queryParams.wcUserName" @keyup.enter.native="handleQuery" placeholder="请输入微信名称"
                    clearable />
            </el-form-item>
            <el-form-item label="电话号码" prop="wcUserPhone">
                <el-input v-model="queryParams.wcUserPhone" @keyup.enter.native="handleQuery" placeholder="请输入电话号码"
                    clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>


        <!-- 信息部分框 -->
        <el-card class="box-card" v-for="(item, idx) in wcAssistGreetInfoList" :key="idx">
            <div slot="header" class="clearfix">
                <img :src="item.wcUserImg" width="50px" height="50px">
                <div class="clearfix-info">
                    <span class="span_one">{{ item.wcUserName }}</span>
                    <span class="span_two">{{ item.wcUserPhone}}</span>
                </div>
                <i class="el-icon-message-solid" @click="openTagDialog(item)"></i>
            </div>
            <div class="text item" id="item">
                <div class="item_one">客户标签</div>
                <div class="item_two">
                    <span v-for="(tag, tagIdx) in item.lableNames" :key="tagIdx">{{ tag }}</span>
                </div>
                <div class="item_three">最近聊天</div>
                <div class="item_four">{{ item.lastChatTime }}</div>
            </div>
        </el-card>
        <el-empty v-if="wcAssistGreetInfoList==null||wcAssistGreetInfoList==''" :description="index==0?'暂无活跃客户信息':index==1?'暂无最新客户信息':'暂无全部客户信息'"></el-empty>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" :pageSizes="pageSizes"/>

        <!-- 添加或修改助手信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="设置标签" prop="assistGreet">
                    <el-select v-model="value" multiple filterable allow-create default-first-option placeholder="请选择标签">
                        <el-option v-for="(tag, index) in assistGreetOptions" :key="index" :label="tag" :value="tag">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitTags">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>
  
<script>
import moment from "moment";
import request from '@/utils/request'
export default {
    name: "WcAssistGreetInfo",
    props: {
      idx: {
        type: Number,
        default: 0,
      },
    },
    data() {
        return {
            index:0,
            value: [],//代替form.assistGreet
            assistGreetOptions: [], // 标签选项列表
            form: {
                assistGreet: [], // 存储被选中的标签
                // wcId: null // 存储当前客户的微信ID
                wcUserId: null, // 存储当前客户的微信用户ID
                index: null // 存储当前客户在列表中的索引
            },
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 助手招呼语设置表格数据
            wcAssistGreetInfoList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            pageSizes: [8,16,24,32],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 8,
                //pageSize: 10,
                wcUserName: null,
                wcUserPhone: null,
                startTime: null, // 最近聊天时间 开始
                endTime: null, // 最近聊天时间 结束
                newTime: null, // 好友添加时间 开始
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
            }
        };
    },
    watch: {
        idx: {
            handler(newValue,oldValue){
                this.init()
            },
            deep: true
        }
    },
    mounted() {
        this.getListceshi()
        this.getList()
    },
    methods: {
        init(){
           this.index=this.idx
           this.queryParams.pageNum = 1
           this.getList()
        },
        getListceshi() {
            getWcAssistGreetInfo().then(res => {
                const items = res.data.records;
                this.assistGreetOptions = [];
                items.map(item => item.tagName).forEach(tagName => {
                    if (tagName) { // 添加判断，确保tagName存在
                        this.assistGreetOptions.push(tagName);
                    }
                });
            });
        },
        handleChange(val){
           this.queryParams.pageNum=val
           this.getList()
        },
        openTagDialog(item) {
            this.form.wcUserId = item.wcUserId; // 存储当前客户的微信用户ID
            this.value = item.lableNames; // 加载当前客户的标签数据
            this.open = true; // 打开对话框
            this.title = "设置标签"; // 设置对话框标题
        },
        submitTags() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.value.length > 0) { // 检查是否有至少一个标签被选中
                        const data = {
                            wcId: this.form.wcUserId,
                            tagNames: this.value // 发送数组
                        };
                        updateTags(data).then(response => {
                            // 更新前端列表中的标签
                            const index = this.wcAssistGreetInfoList.findIndex(customer => customer.wcUserId === this.form.wcUserId);
                            if (index !== -1) {
                                this.wcAssistGreetInfoList[index].lableNames = this.value;
                            }
                            this.$modal.msgSuccess("标签设置成功");
                            this.open = false;
                            // 重新获取数据列表
                            this.getList(); // 如果您不打算从服务器重新获取数据，注释掉这行
                        });
                    } else {
                        this.$modal.alert("请选择至少一个标签");
                    }
                }
            });
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            var lastTime=moment().format('YYYY-MM-DD HH:mm:ss');
            var startTime=moment(lastTime).add(-3, 'days').format('YYYY-MM-DD HH:mm:ss');
            if(this.index==2){
                this.queryParams.endTime = null
                this.queryParams.startTime = null
                this.queryParams.newTime=null
            }else{
                if(this.index==1){
                    this.queryParams.endTime = null
                    this.queryParams.startTime = null
                    this.queryParams.newTime=startTime
                }else{
                    this.queryParams.newTime=null
                    this.queryParams.startTime = startTime
                    this.queryParams.endTime = lastTime
                }
            }
            listWcAssistGreetInfo(this.queryParams).then(res => {
                this.wcAssistGreetInfoList = res.data.rows;
                const dt = res['data'];
                this.total = dt['total'];
                this.loading = false;
            });
            setTimeout(()=>{
              this.loading = false;
            },2000)
        },     
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                assistId: null,
                wcUserName: null,
                assistGreet: null,
                assistJob: null,
                assistAge: null,
                assistNature: null,
                remark: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                delFlag: null,
                lastChatTime: null,
                wcUserPhone: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "设置标签";

        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getWcAssistGreetInfo(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "设置标签";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateWcAssistGreetInfo(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addWcAssistGreetInfo(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除助手招呼语设置编号为"' + ids + '"的数据项？').then(function () {
                return delWcAssistGreetInfo(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('arbit/wcassist_greet_info/export', {
                ...this.queryParams
            }, `wcAssistGreetInfo_${new Date().getTime()}.xlsx`)
        }
    }
};

/** js请求 调用 */
// 修改
export function updateTags(data) {
    return request({
        url: '/wxassistant/wclocal_tags_info/EditTags',
        method: 'post',
        data: data
    })
}

export function listWcAssistGreetInfo(query) {
    return request({
        url: '/skmodulemoments/wcFriendInfo/GetFriendInfo',
        method: 'post',
        params: query
    })
}


// // 查询
export function getWcAssistGreetInfo() {
    return request({
        url: '/wxassistant/wctags_info/page',
        method: 'get'
    })
}

// 新增
export function addWcAssistGreetInfo(data) {
    return request({
        url: '/arbit/wcassist_greet_info/add',
        method: 'post',
        data: data
    })
}

// 修改
export function updateWcAssistGreetInfo(data) {
    return request({
        url: '/arbit/wcassist_greet_info/edit',
        method: 'put',
        data: data
    })
}

// 删除
export function delWcAssistGreetInfo(id) {
    return request({
        url: '/arbit/wcassist_greet_info/delete/' + id,
        method: 'delete'
    })
}

</script>
<style lang="scss" scoped>
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}



.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}


// 信息框部分样式
.box-card {
    margin-top: 20px;
    width: 23%;
    margin-right: 2%;
    // width: 400px;
    height: 260px;
    float: left;
    margin-bottom: 20px;

    .clearfix {
        display: flex;
        img {
            border-radius: 50%;
        }
        .clearfix-info{
            width: 65%;margin-left: 10px;display: flex;flex-direction: column;margin-right:5%;
            .span_one{
                overflow: hidden; /* 确保超出容器的文本被隐藏 */
                white-space: nowrap; /* 防止文本换行 */
                text-overflow: ellipsis; /* 用省略号显示被截断的文本 */
            }
            .span_two{
                font-size: 14px;
                line-height: 25px;
                color: #b6bbc0;
            }
        }
        
        .el-icon-message-solid {
            float: right;
            font-size: 23px;
        }
    }

    #item {
        .item_one {
            color: rgb(182, 187, 192);
            margin-bottom: 8px;
        }

        .item_two {
            height: 50px;

            span {
                border: 1px dashed rgb(136, 191, 207);
                font-size: 20px;
                font-weight: bold;
                padding: 4px;
                margin-right: 5px;
                margin-top: 5px;
                display: inline-block;
                /* 将span设置为内联块级元素 */
                margin-right: 5px;
                margin-bottom: 5px;
                /* 为相邻的span添加右外边距 */
            }
        }

        .item_three {
            color: rgb(182, 187, 192);
            margin-top: 10px;
        }

        .item_four {
            margin-top: 10px
        }
    }

}

.pagination-container {
    // 清除浮动，确保分页组件能够显示在卡片下面
    clear: both;
    // 如果需要，可以添加一些边距
    margin-top: 20px;
    position: relative;
    height: 0px;
    margin-bottom: 0px;
    margin-top: 0px;
    padding: 0px 0px;
    background:#f6f9fb;
}
</style>